#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QFile>
#include <QDir>

#include "imagedownloader.h"
#include "utils.h"

namespace Jcr
{

class ImageDownloaderPrivate
{
public:
    ~ImageDownloaderPrivate();
    QNetworkAccessManager* netMgr = nullptr;
    QNetworkReply* netReply = nullptr;
    QUrl url;
    QString saveDir;
    QString saveName;
};

ImageDownloaderPrivate::~ImageDownloaderPrivate()
{
    if (netMgr)
        delete netMgr;
}

ImageDownloader::ImageDownloader(const QUrl& url, const QString& saveDir, QObject *parent) : QObject(parent)
{
    d_ptr = new ImageDownloaderPrivate;
    d_ptr->url = url;
    d_ptr->saveDir = saveDir;
}

ImageDownloader::~ImageDownloader()
{
    delete d_ptr;
}

void ImageDownloader::setSaveName(const QString& name)
{
    d_ptr->saveName = name;
    d_ptr->saveName.replace("\\", "-");
    d_ptr->saveName.replace("/", "-");
}

QString ImageDownloader::saveName() const
{
    return d_ptr->saveName;
}

QString ImageDownloader::localPath() const
{
    QString imageName;
    if (d_ptr->saveName.isEmpty())
        imageName = Jcr::Utils::fileNameFromUrl(d_ptr->url);
    else
        imageName = QString("%1.%2").arg(d_ptr->saveName).arg(Jcr::Utils::fileExtFromUrl(d_ptr->url));

    QString path = d_ptr->saveDir + "/" + imageName;
    return path;
}

QUrl ImageDownloader::url() const
{
    return d_ptr->url;
}

void ImageDownloader::run()
{
    if (d_ptr->url.isEmpty()) {
        emit finished();
        return;
    }

    if (!d_ptr->netMgr) {
        d_ptr->netMgr = new QNetworkAccessManager(this);
        connect(d_ptr->netMgr, SIGNAL(finished(QNetworkReply*)), this, SLOT(onDownloadCompleted(QNetworkReply*)));
    }

    QNetworkRequest request;
    request.setUrl(d_ptr->url);
    d_ptr->netMgr->get(request);
}

void ImageDownloader::onDownloadCompleted(QNetworkReply *reply)
{
    QString imageName;
    if (d_ptr->saveName.isEmpty())
        imageName = Jcr::Utils::fileNameFromUrl(d_ptr->url);
    else
        imageName = QString("%1.%2").arg(d_ptr->saveName).arg(Jcr::Utils::fileExtFromUrl(d_ptr->url));

    QString imageFile = QDir::toNativeSeparators(d_ptr->saveDir + "/" + imageName);
    QFile file;
    file.setFileName(imageFile);
    if (!file.open(QIODevice::WriteOnly)) {
        qDebug() << "Failed to open file to write { code:" << file.error() << " desc: " << file.errorString() << "}";
        emit finished();
        return;
    }

    QByteArray result = reply->readAll();
    file.write(result);
    file.close();
    emit finished();

    deleteLater();
}

} // namespace jcr
